<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="deptName"
              placeholder="请输入部门名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              default-expand-all
              @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" class="bg-white p-1">
          <el-form-item label="用户名称" prop="account">
            <el-input
                v-model="queryParams.query.name"
                placeholder="请输入用户名称"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input
                v-model="queryParams.query.phone"
                placeholder="请输入手机号码"
                clearable
                size="small"
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="abled">
            <el-select
                v-model="queryParams.query.abled"
                placeholder="用户状态"
                clearable
                size="small"
                style="width: 240px"
            >
              <el-option
                  v-for="dict in abledOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="创建时间">-->
          <!--            <el-date-picker-->
          <!--                v-model="dateRange"-->
          <!--                size="small"-->
          <!--                style="width: 240px"-->
          <!--                value-format="yyyy-MM-dd"-->
          <!--                type="daterange"-->
          <!--                range-separator="-"-->
          <!--                start-placeholder="开始日期"-->
          <!--                end-placeholder="结束日期"-->
          <!--            ></el-date-picker>-->
          <!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8 my-1">
          <el-col :span="1.5">
            <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                v-hasPermi="['system:user:add']"
            >新增
            </el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="userList" :header-cell-style="{background: '#DDD'}">
          <el-table-column label="用户账号" align="center" key="userName" prop="account" width="120"/>
          <el-table-column label="用户姓名" align="center" key="name" prop="name" width="120"/>
          <el-table-column label="部门" align="center" key="deptName" prop="deptName" width="120"/>
          <el-table-column label="手机号码" align="center" key="phone" prop="phone" width="120"/>
          <el-table-column label="拥有角色" align="center" key="roleNames" prop="roleNames" :show-overflow-tooltip="true"/>
          <el-table-column label="状态" align="center" key="abled">
            <template slot-scope="scope">
              <el-switch
                  v-if="scope.row.id !== '-1'"
                  v-model="scope.row.abled"
                  active-value="1"
                  inactive-value="0"
                  @change="handleAbledChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="主管" align="center" key="sfCharge">
            <template slot-scope="scope">
              <el-switch
                  v-if="scope.row.id !== '-1'"
                  v-model="scope.row.sfCharge"
                  active-value="1"
                  inactive-value="0"
                  @change="handleSetCharge(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <!--          <el-table-column label="创建时间" align="center" prop="createTime" width="180">-->
          <!--            <template slot-scope="scope">-->
          <!--              <span>{{ parseTime(scope.row.createTime) }}</span>-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column
              label="操作"
              align="center"
              width="240"
              class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                  v-if="scope.row.id !== '-1'"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:user:edit']"
              >修改
              </el-button>
              <el-button
                  v-if="scope.row.id !== '-1'"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:user:remove']"
              >删除
              </el-button>
              <el-button
                  v-if="scope.row.id !== '-1'"
                  size="mini"
                  type="text"
                  @click="resetPwd(scope.row)"
                  v-hasPermi="['system:user:remove']"
              >重置密码
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.id === undefined" label="用户账号" prop="account">
              <el-input v-model="form.account" placeholder="请输入用户账号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id === undefined" label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入用户姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="form.roleIds" multiple placeholder="请选择">
                <el-option
                    v-for="item in roleOptions"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.abled">
                <el-radio
                    v-for="dict in abledOptions"
                    :key="dict.dictValue"
                    :label="dict.dictValue"
                >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <czDialog v-if="isShowCz" :isShowCz="isShowCz" :rowData="rowData" @dialogClose="dialogClose"></czDialog>
  </div>
</template>

<script>
import {userPage, userInfo, userDelete, userAdd, userUpdate, changeUserAbled,setCharge} from "@/api/sys/user";
import {deptTreeSelect} from "@/api/sys/dept";
import {roleList} from "@/api/sys/role";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import czDialog from './components/czDialog.vue'

export default {
  name: "User",
  components: {Treeselect, czDialog},
  data() {
    return {
      isShowCz: false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      abledOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        query: {
          account: undefined,
          phone: undefined,
          abled: undefined,
          deptId: undefined
        }
      },
      // 表单校验
      rules: {
        name: [
          {required: true, message: "用户姓名不能为空", trigger: "blur"}
        ],
        deptId: [
          {required: true, message: "部门不能为空", trigger: "blur"}
        ],
        account: [
          {required: true, message: "用户账号不能为空", trigger: "blur"}
        ],
        password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"}
        ],
        phone: [
          {
            required: false,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTreeSelect();
    this.getDicts("if_abled").then(response => {
      this.abledOptions = response.data;
    });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      userPage(this.addDateRange(this.queryParams, this.dateRange))
          .then(response => {
                this.userList = response.data.rows;
                this.total = response.data.total;
                this.loading = false;
              }
          );
    },
    /** 查询部门下拉树结构 */
    getDeptTreeSelect() {
      deptTreeSelect({}).then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 获取角色列表 */
    getRoleList() {
      roleList({}).then(response => {
        this.roleOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.query.deptId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleAbledChange(row) {
      let text = row.abled === "1" ? "启用" : "禁用";
      this.$confirm('确认要"' + text + '""' + row.name + '"用户吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeUserAbled({
          id: row.id,
          abled: row.abled
        });
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.abled = row.abled === "0" ? "1" : "0";
      });
    },
    // 设置用户主管
    handleSetCharge(row) {
      let text = row.sfCharge === '1' ? "确认要设置"+ row.name+"为主管么？" : "确认要取消"+ row.name+"的主管么？";
      this.$confirm(text, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return setCharge({
          id: row.id,
          sfCharge: row.sfCharge
        });
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.sfCharge = row.sfCharge === 0 ? 1 : 0;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        deptId: undefined,
        account: undefined,
        name: undefined,
        password: undefined,
        phone: undefined,
        abled: "1",
        roleIds: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        query: {
          account: undefined,
          phone: undefined,
          abled: undefined,
          deptId: undefined
        }
      };
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDeptTreeSelect();
      this.getRoleList();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getDeptTreeSelect();
      this.getRoleList();
      const userId = row.id;
      userInfo(userId).then(response => {
        this.form = response.data;
        this.form.roleIds = response.data.roleIds;
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            userUpdate(this.form).then(() => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            userAdd(this.form).then(() => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userId = row.id;
      this.$confirm('是否确认删除该用户?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return userDelete(userId);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    // 点击重置密码
    resetPwd(row) {
      this.rowData = row
      this.isShowCz = true
    },
    dialogClose(isSearchReset = false) {
      this.isShowCz = false;
      this.rowData = null;
      if (isSearchReset) {
        this.getList();
        this.msgSuccess("重置成功");
      }
    },
  }
};
</script>
